//
//  MyViewController.m
//  何五路
//
//  Created by _ADY on 15/6/5.
//  Copyright (c) 2015年 _ADY. All rights reserved.
//

#import "MyViewController.h"
#import "LoginViewController.h"
#import "AllOrderViewController.h"
#import "SetViewController.h"
#import "SetMyViewController.h"
#import "UIButton+CustomBadge.h"

@interface MyViewController ()

@end

@implementation MyViewController
@synthesize allArray,numArray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"我的";
        dfkInt = 0;
        self.view.backgroundColor = bgColor;
    }
    return self;
}

-(void)leftAction
{
    SetViewController *browser = [[SetViewController alloc] init];
    browser.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:browser animated:YES];
}

-(void)rightAction
{
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"setting"] style:UIBarButtonItemStylePlain target:self action:@selector(leftAction)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"message"] style:UIBarButtonItemStylePlain target:self action:@selector(rightAction)];
    
    
    mTableView = [[UITableView alloc] initWithFrame:tableFrame style:UITableViewStyleGrouped];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.sectionHeaderHeight = 0.0;
    mTableView.sectionFooterHeight = 0.0;
    mTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mTableView];
    
    
//    __weak __typeof(self) weakSelf = self;
//    
//    mTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [weakSelf loadNewData];
//    }];
    
    isLogin = NO;
    allArray = [[NSDictionary alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(treatedATask) name:kTreatedCompleteNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(treatedATask1) name:kTreatedCompleteNotification1 object:nil];
    
    [self treatedATask];
}

-(void)treatedATask1
{
    isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"isLoginKey"];
    if (numArray != nil) {
        numArray = nil;
    }
    dfkInt = dshInt = dpjInt = 0;
    [mTableView reloadData];
}
-(void)treatedATask
{
    if (![SendService userAccount] || ![SendService password])
    {
        return;
    }
    
    NSMutableDictionary *postDic = [[NSMutableDictionary alloc] init];
    [postDic setObject:[SendService userAccount] forKey:@"username"];
    [postDic setObject:[SendService password] forKey:@"password"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSDictionary *ret = [SendService Login:postDic];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (ret !=nil)
            {
                NSLog(@"ret %@",ret);
                
                if ([[ret objectForKey:@"Result"] isEqualToString:@"success"])
                {
                    allArray =  [ret objectForKey:@"Entity"];
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isLoginKey"];
                    
                }
                else
                {
                    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isLoginKey"];
                }
                isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"isLoginKey"];
               
                [mTableView reloadData];
            }
            
        });
    });
 
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadNewData];
}
- (void)loadNewData
{
    if (!isLogin)
    {
//        [mTableView.header endRefreshing];
        return;
    }

    NSMutableDictionary *postDic1 = [[NSMutableDictionary alloc] init];
    [postDic1 setObject:@"10" forKey:@"orderStatus"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSDictionary *ret = [SendService GetOrderNum:postDic1];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (ret !=nil)
            {
                if (![[NSString stringWithFormat:@"%@",[ret objectForKey:@"Result"]] isEqualToString:@"error"])
                {
                    dfkInt = [[ret objectForKey:@"Entity"] intValue];
                }
                [mTableView reloadData];
            }
            
        });
    });
    
    NSMutableDictionary *postDic2 = [[NSMutableDictionary alloc] init];
    [postDic2 setObject:@"25" forKey:@"orderStatus"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSDictionary *ret = [SendService GetOrderNum:postDic2];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (ret !=nil)
            {
                if (![[NSString stringWithFormat:@"%@",[ret objectForKey:@"Result"]] isEqualToString:@"error"])
                {
                    dshInt = [[ret objectForKey:@"Entity"] intValue];
                }
                [mTableView reloadData];
            }
            
        });
    });
    
    NSMutableDictionary *postDic3 = [[NSMutableDictionary alloc] init];
    [postDic3 setObject:@"30" forKey:@"orderStatus"];
    [postDic3 setObject:@"1" forKey:@"commentStatus"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSDictionary *ret = [SendService GetOrderNum:postDic3];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (ret !=nil)
            {
                if (![[NSString stringWithFormat:@"%@",[ret objectForKey:@"Result"]] isEqualToString:@"error"])
                {
                    dpjInt = [[ret objectForKey:@"Entity"] intValue];
                }
                [mTableView reloadData];
            }
            
        });
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSDictionary *ret = [SendService GetShoppingCartCount];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (ret !=nil)
            {
                NSLog(@"获取用户购物车收藏夹数量接口 %@",ret);
 
                numArray = [[NSDictionary alloc] init];
                numArray = [ret objectForKey:@"Entity"];
                [mTableView reloadData];
            }
            
        });
    });
    
   
}


#pragma mark -
#pragma mark Table View DataSource

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
        return 0.001;
    return 10;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 ||section == 3 ||section == 4)
        return 1;
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
        return 142*screenMySize.size.width/320;
    else if (indexPath.section == 1 ||indexPath.section == 2)
    {
        if (indexPath.row == 0) {
            return 40;
        }
        else
            return 70;
    }
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        aTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        aTableView.showsVerticalScrollIndicator = NO;
    }
    int i = (int)[[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
        [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }
    cell.backgroundColor = [UIColor whiteColor];
    
    if (indexPath.section == 0)
        return [self mCell:cell aCTableView:aTableView cellForRowAtIndexPath:indexPath];
    else if (indexPath.section == 1)
        return [self mCell:cell bCTableView:aTableView cellForRowAtIndexPath:indexPath];
    else if (indexPath.section == 2)
        return [self mCell:cell cCTableView:aTableView cellForRowAtIndexPath:indexPath];
    else if (indexPath.section == 6)
        return [self mCell:cell dCTableView:aTableView cellForRowAtIndexPath:indexPath];
    else if (indexPath.section == 3)
        return [self mCell:cell eCTableView:aTableView cellForRowAtIndexPath:indexPath];
    // Configure the cell...
    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell aCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, screenMySize.size.width, 142*screenMySize.size.width/320)];
    [cell.contentView addSubview:bgImageView];
    
    int typeInt = 3;
    if (isLogin)
    {
        [bgImageView setImage:[UIImage imageNamed:@"user_bg"]];
        typeInt = 3;
        
        UIImageView *imageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"user_unlogin_bg"]];
        imageView1.frame = CGRectMake(10,10, 60, 60);
        imageView1.layer.masksToBounds = YES;
        imageView1.layer.cornerRadius = 30;
        [cell.contentView addSubview:imageView1];
        
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(80,10, screenMySize.size.width-80, 30)];
        titleLabel.text = [NSString stringWithFormat:@"%@",[allArray objectForKey:@"NickName"]];
        titleLabel.textAlignment = 0;
        titleLabel.font = [UIFont fontWithName:@"Arial" size:labelSize+2];
        titleLabel.textColor = [UIColor whiteColor];
        [cell.contentView addSubview:titleLabel];
        
        UIButton *bgButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [bgButton setFrame:CGRectMake(75, 40, 150, 20)];
        bgButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-1];
        [bgButton setTitle:@"账号管理、收货地址>" forState:UIControlStateNormal];
        [bgButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [bgButton addTarget:self action:@selector(accoutAction) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:bgButton];
 
    }
    else
    {
        [bgImageView setImage:[UIImage imageNamed:@"user_unlogin_bg"]];
        
        UIButton *bgButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [bgButton setFrame:CGRectMake(screenMySize.size.width/2-30, 25, 60, 60)];
        [bgButton setBackgroundImage:[UIImage imageNamed:@"unlogin_circle"] forState:UIControlStateNormal];
        [bgButton addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:bgButton];

    }
    
    for (int i = 0; i < 4; i ++)
    {
        if (typeInt == 3 && i == 3) {
            break;
        }
        UIButton *bgButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [bgButton setFrame:CGRectMake(0, 0, screenMySize.size.width/typeInt-2.5, 40)];
        [bgButton setBackgroundColor:[UIColor colorWithWhite:0 alpha:.1]];
        bgButton.center = CGPointMake((screenMySize.size.width+2.5)*i/typeInt+screenMySize.size.width/(typeInt*2),142*screenMySize.size.width/320-40/2);
        bgButton.tag = 10+i;
        [bgButton addTarget:self action:@selector(aInBction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:bgButton];
        
        NSArray *titArray = [NSArray arrayWithObjects:@"关注的商品",@"关注的店铺",@"浏览记录", nil];
//        NSArray *titArray = [NSArray arrayWithObjects:@"关注的商品",@"关注的店铺",@"关注的活动",@"浏览记录", nil];
        if (isLogin)
        {
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0, screenMySize.size.width/typeInt-2.5, 20)];
            if (i == 0)
            {
                titleLabel.text = [NSString stringWithFormat:@"%@",[numArray objectForKey:@"WishlistCount"]];
            }
            else if (i == 1)
                titleLabel.text = [NSString stringWithFormat:@"%@",[numArray objectForKey:@"FavoriteShopCount"]];
            titleLabel.textAlignment = 1;
            titleLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-2];
            titleLabel.textColor = [UIColor whiteColor];
            [bgButton addSubview:titleLabel];
        }

        
        UILabel *title1Label = [[UILabel alloc] init];
        if (isLogin)
             title1Label.frame = CGRectMake(0,20, screenMySize.size.width/typeInt-2.5, 20);
        else
            title1Label.frame = CGRectMake(0,10, screenMySize.size.width/typeInt-2.5, 20);
        title1Label.text = [titArray objectAtIndex:i];
        title1Label.textAlignment = 1;
        title1Label.font = [UIFont fontWithName:@"Arial" size:labelSize-1];
        title1Label.textColor = [UIColor whiteColor];
        [bgButton addSubview:title1Label];
        
        
    }
    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell bCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        cell.imageView.image = [UIImage imageNamed:@"my_order"];
        cell.textLabel.text = @"我的订单";
        cell.textLabel.textAlignment = 0;
        cell.textLabel.textColor = [UIColor blackColor];
        cell.detailTextLabel.text = @"查看全部订单 >";
        cell.detailTextLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-2];
        cell.detailTextLabel.textAlignment = 2;
    }
    else if (indexPath.row == 1) {
        [cell.contentView addSubview:[self setTitle:@"待付款" setImage:[UIImage imageNamed:@"dfjk"] setTage:0 setTag:1]];
        UIButton *inButton = (UIButton *)[self.view viewWithTag:1];
        [inButton setBadgeWithNumber:[NSNumber numberWithInt:dfkInt]];
        
        [cell.contentView addSubview:[self setTitle:@"待收货" setImage:[UIImage imageNamed:@"dsh"] setTage:1 setTag:2]];
        UIButton *in1Button = (UIButton *)[self.view viewWithTag:2];
        [in1Button setBadgeWithNumber:[NSNumber numberWithInt:dshInt]];
        
        [cell.contentView addSubview:[self setTitle:@"待评价" setImage:[UIImage imageNamed:@"dpj"] setTage:2 setTag:3]];
        UIButton *in2Button = (UIButton *)[self.view viewWithTag:3];
        [in2Button setBadgeWithNumber:[NSNumber numberWithInt:dpjInt]];
        
        [cell.contentView addSubview:[self setTitle:@" 售后 " setImage:[UIImage imageNamed:@"sh"] setTage:3 setTag:4]];
    }
    
    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell cCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        cell.imageView.image = [UIImage imageNamed:@"my_card"];
        cell.textLabel.text = @"我的钱包";
        cell.textLabel.textAlignment = 0;
        cell.textLabel.textColor = [UIColor blackColor];
//        cell.detailTextLabel.text = @"金元宝/银元宝 五路财神卡 >";
//        cell.detailTextLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-2];
//        cell.detailTextLabel.textAlignment = 2;
    }
    else if (indexPath.row == 1) {
        [cell.contentView addSubview:[self setTitle:TKjyb setImage:[UIImage imageNamed:@"my_account"] setTage:0 setTag:5]];
        [cell.contentView addSubview:[self setTitle:TKyyb setImage:[UIImage imageNamed:@"my_account"] setTage:1 setTag:6]];
        [cell.contentView addSubview:[self setTitle:@"优惠劵" setImage:[UIImage imageNamed:@"yhq"] setTage:2 setTag:7]];
        [cell.contentView addSubview:[self setTitle:@" 返利 " setImage:[UIImage imageNamed:@"fx"] setTage:3 setTag:8]];
    }

    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell dCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.imageView.image = [UIImage imageNamed:@"my_server"];
    cell.textLabel.text = @"我的服务";
    cell.textLabel.textAlignment = 0;
    cell.textLabel.textColor = [UIColor blackColor];
    cell.detailTextLabel.text = @"物流查询/到货提醒 >";
    cell.detailTextLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-2];
    cell.detailTextLabel.textAlignment = 2;
    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell eCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.imageView.image = [UIImage imageNamed:@"hyzx"];
    cell.textLabel.text = @"会员中心";
    cell.textLabel.textAlignment = 0;
    cell.textLabel.textColor = [UIColor blackColor];
    cell.detailTextLabel.text = @"积分/会员等级/分享历史 >";
    cell.detailTextLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-2];
    cell.detailTextLabel.textAlignment = 2;
    return cell;
}

-(UIButton*)setTitle:(NSString *)title setImage:(UIImage*)imageD setTage:(int)tyPage setTag:(int)theTag
{
    CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Arial" size:labelSize-1]}];
    
    UIButton *inButton = [UIButton buttonWithType:UIButtonTypeCustom];
    CGRect frame = CGRectMake(0,0, screenMySize.size.width/4,70);
    [inButton setImage:imageD forState:UIControlStateNormal];
    [inButton setFrame:frame];
    [inButton setTitleEdgeInsets:UIEdgeInsetsMake(imageD.size.height+5, 0, 0, 0)];
    [inButton setImageEdgeInsets:UIEdgeInsetsMake(-titleSize.height-10, (screenMySize.size.width/4-imageD.size.width)/2, 0, 0)];
    
    [inButton setTitle:title forState:UIControlStateNormal];
    [inButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    inButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-1];
    inButton.center = CGPointMake(screenMySize.size.width*tyPage/4+screenMySize.size.width/8, 70/2);
    inButton.tag = theTag;
    [inButton addTarget:self action:@selector(bInBction:) forControlEvents:UIControlEventTouchUpInside];
    return inButton;
}

-(void)aInBction:(id)sender
{
    if (!isLogin) {
        [self loginAction];
        return;
    }
    
    int  type = ((UIButton*)sender).tag -10;
    if (type == 0 || type == 1)
    {
        MyWishListViewController *details = [[MyWishListViewController alloc] init];
        details.hidesBottomBarWhenPushed = YES;
        details.aInt = type;
        [self.navigationController pushViewController:details animated:YES];
    }

}

-(void)bInBction:(id)sender
{
    if (!isLogin) {
        [self loginAction];
        return;
    }
    int  type = ((UIButton*)sender).tag;
    if (type == 1 || type == 2 || type == 3)
    {
        NSArray *array = [NSArray arrayWithObjects:@"待付款",@"待收货",@"待评价", nil];
        AllOrderViewController *details = [[AllOrderViewController alloc] init];
        details.hidesBottomBarWhenPushed = YES;
        details.allString = [NSString stringWithFormat:@"%d",type];
        details.title = [array objectAtIndex:type-1];
        [self.navigationController pushViewController:details animated:YES];
    }
    else if (type == 7)
    {
        MyYhqViewController *details = [[MyYhqViewController alloc] init];
        details.hidesBottomBarWhenPushed = YES;
        details.title = @"优惠券";
        [self.navigationController pushViewController:details animated:YES];
    }
    else if (type == 5 || type == 6 || type == 8)
    {
        JYYBViewController *details = [[JYYBViewController alloc] init];
        details.hidesBottomBarWhenPushed = YES;
        if (type == 5) {
            details.title = TKjyb;
        }
        else if (type == 6)
            details.title = TKyyb;
        else if (type == 8)
            details.title = TKfl;
        [self.navigationController pushViewController:details animated:YES];
    }
}

-(void)loginAction
{
    LoginViewController *browser = [[LoginViewController alloc] init];
//    [self presentViewController:browser animated:YES completion:nil];
    browser.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:browser animated:YES];
}

-(void)accoutAction
{
    SetMyViewController *browser = [[SetMyViewController alloc] init];
    browser.hidesBottomBarWhenPushed = YES;
    browser.allArray = allArray;
    [self.navigationController pushViewController:browser animated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section == 1)
    {
        if (indexPath.row == 0)
        {
            if (!isLogin) {
                [self loginAction];
                return;
            }
            AllOrderViewController *details = [[AllOrderViewController alloc] init];
            details.hidesBottomBarWhenPushed = YES;
            details.allString = [NSString stringWithFormat:@"%d",0];
            details.title = @"全部订单";
            [self.navigationController pushViewController:details animated:YES];
        }
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
